package edu.jkd.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import edu.jkd.config.UploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Component
public class QiniuUtils {

    private UploadManager uploadManager;

    private Auth auth;

    @Value("${qiniu.bucketName}")
    private String bucketName;
    @Value("${qiniu.path}")
    private String url;

    public String upload(byte[] bytes,String fileName) throws QiniuException {
        auth = UploadConfig.getAuth();
        uploadManager = UploadConfig.getUploadManager();
        String token = auth.uploadToken("bucket202211");
        String url = null;
        Response res = null;
        String imgName = null;
        String key = fileName;//七牛云服务器里用来对应唯一上传的文件
        try {
            res = uploadManager.put(bytes, key, token);
            imgName = (String) res.jsonToMap().get("key");
            url = bucketName+imgName; // url = 域名+文件名
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return url;
    }

}